package com.ctw.tinyservices.id.sdk;

import com.ctw.tinyservices.id.common.lifecycle.AbstractIdLifecycle;
import com.ctw.tinyservices.id.common.utils.LogUtils;
import com.ctw.tinyservices.id.sdk.config.IdSdkConfig;
import com.ctw.tinyservices.id.sdk.segment.IdSegmentSdk;
import com.ctw.tinyservices.id.sdk.support.DefaultIdConfigSupport;
import com.ctw.tinyservices.id.sdk.support.IdConfigSupport;
import com.google.common.base.Strings;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author TongWei.Chen 2022/3/17 19:29
 *
 * AbstractIdSdk
 **/
public abstract class AbstractIdSdk extends AbstractIdLifecycle {
    private static String serverUrl = "{0}/sdk/";

    protected IdConfigSupport idConfigSupport;
    protected String location;

    @Override
    public String name() {
        return "idSdk";
    }

    public abstract Long getId(String bizType);

    public AbstractIdSdk registerConfigSupport() {
        return registerConfigSupport(new DefaultIdConfigSupport(location));
    }

    public AbstractIdSdk registerConfigSupport(IdConfigSupport idConfigSupport) {
        if (null != this.idConfigSupport) {
            return this;
        }
        synchronized (AbstractIdSdk.class) {
            if (null == this.idConfigSupport) {
                this.idConfigSupport = idConfigSupport;
                LogUtils.info(AbstractIdSdk.class, "idConfig register success ");
                init();
            }
        }
        return this;
    }

    @Override
    protected void doInit() {
        String tinyIdServer = idConfigSupport.getServerUrl();
        int readTimeout = idConfigSupport.getReadTimeout();
        int connectTimeout = idConfigSupport.getConnectTimeout();
        String bizToken = idConfigSupport.getBizToken();

        if (Strings.isNullOrEmpty(tinyIdServer)) {
            throw new IllegalArgumentException("cannot find tinyservices.id.server config");
        }
        IdSdkConfig idSdkConfig = IdSdkConfig.getInstance();
        idSdkConfig.setReadTimeout(readTimeout);
        idSdkConfig.setConnectTimeout(connectTimeout);
        idSdkConfig.setBizToken(bizToken);

        String[] tinyIdServers = tinyIdServer.split(",");
        List<String> serverList = new ArrayList<>(tinyIdServers.length);
        for (String server : tinyIdServers) {
            String url = MessageFormat.format(serverUrl, server);
            serverList.add(url);
        }
        idSdkConfig.setServerList(serverList);
        LogUtils.info(IdSegmentSdk.class, "init tinyservices-id sdk success url info:[{}]", serverList);
    }
}
